package znzz.db.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import znzz.db.util.MongoDBUtil;
import znzz.db.util.TableAndAttrUtil;

import java.util.List;

/**
 * MongoDB 数据同步
 * <p/>
 * Created by wangjwm on 2017/7/5.
 */
@Controller
@RequestMapping(value = "/dbsync")
public class DBSyncCtrl {

    @Autowired
    @Qualifier("tableAndAttrUtil")
    private TableAndAttrUtil tableAndAttrUtil;

    /**
     * 获得数据库表名
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/doucment", method = RequestMethod.GET)
    public List<String> getDocumentNames() {
        // 集合名称
        String dbName = MongoDBUtil.instance.getMongoConfigVO().getCollectionname();
        // 获得所有数据库名称
        return MongoDBUtil.instance.getAllCollections(dbName);
    }

    /**
     * 数据表同步
     *
     * @param tableName 表名
     */
    @ResponseBody
    @RequestMapping(value = "/{tableName}/document", method = RequestMethod.POST)
    public int syncDocumentToSQL(@PathVariable String tableName) {
        return tableAndAttrUtil.getiSyncServiceMap().get(tableName).syncDocuments(tableName);
    }

    /**
     * 数据表清空
     *
     * @param tableName 表名
     */
    @ResponseBody
    @RequestMapping(value = "/{tableName}/clear", method = RequestMethod.DELETE)
    public int clearSQL(@PathVariable String tableName) {
        int size = 0;
        // 获得关联表
        List<String> subTableNames = tableAndAttrUtil.getTable2Sub().get(tableName);
        size += tableAndAttrUtil.getiSyncServiceMap().get(tableName).clearTable(tableName);
        for (String subTableName : subTableNames) {
            size += tableAndAttrUtil.getiSyncServiceMap().get(tableName).clearTable(tableName + "_" + subTableName);
        }
        return size;
    }

}
